package cn.sykj.car.controller;


import cn.sykj.car.common.Const;
import cn.sykj.car.common.ResponseBean;
import cn.sykj.car.common.StatusCode;
import cn.sykj.car.entity.Users;
import cn.sykj.car.service.IUsersService;
import cn.sykj.car.utils.MD5Utils;
import cn.sykj.car.utils.Utils;
import cn.sykj.car.vo.UsersVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.rmi.CORBA.Util;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author Yixu
 * @since 2018-11-29
 */
@Api(hidden = false, tags = {"用户 前端控制器"})
@RestController
@RequestMapping("/users")
public class UsersController extends BaseController {

    // 日志
    private static Logger logger = LoggerFactory.getLogger(UsersController.class);

    @Resource
    private IUsersService iUsersService;

    /**
     * 添加用户，登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "添加用户", notes = "登陆才能操作")
    @ApiImplicitParams({

    })
    @RequiresAuthentication
    @RequiresPermissions("user:create")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
//    public ResponseBean insertUsers(
//            @RequestBody UsersVO usersParam, HttpServletRequest request
//    ) throws Exception {
//
//        // 获取登陆系统用户名，存入日志
//
//        Object obj=SecurityUtils.getSubject().getPrincipal();
//        logger.debug((String) obj);
//
//        // 插入用户
//        UsersVO nUsers = new UsersVO();
//        nUsers.setUserName(usersParam.getUserName());// 用户名
//        nUsers.setPasswd(MD5Utils.getStringMD5(usersParam.getPasswd()));// 密码
//        nUsers.setDelFlag(Const.DEL_FLAG_FALSE);
//
//        if (Utils.notEmpty(usersParam.getRealName())) {// 真实姓名
//            nUsers.setRealName(usersParam.getRealName());
//        }
//        if (Utils.notEmpty(usersParam.getTel())) {// 电话
//            nUsers.setTel(usersParam.getTel());
//        }
//
//        // 角色id集合
//        if (Utils.notEmpty(usersParam.getRoleIds())) {// 角色id集合
//            nUsers.setRoleIds(usersParam.getRoleIds());
//        }
//
//        boolean ret = iUsersService.insertUsers(nUsers);
//        if (ret) {
//            this.writeLog("添加用户");
//        }
//        return new ResponseBean(StatusCode.OK, null);
//    }

    public ResponseBean insertUsers(@RequestBody UsersVO usersParam,HttpServletRequest request
    )throws Exception{
        Object obj=SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        UsersVO nUsers=new UsersVO();
        nUsers.setUserName(usersParam.getUserName());
        nUsers.setPasswd(MD5Utils.getStringMD5(usersParam.getPasswd()));
        nUsers.setDelFlag(Const.DEL_FLAG_FALSE);

        if (Utils.notEmpty(usersParam.getRealName())){
            nUsers.setTel(usersParam.getRealName());
        }
        if (Utils.notEmpty(usersParam.getTel())){
            nUsers.setTel(usersParam.getTel());
        }
        if (Utils.notEmpty(usersParam.getRoleIds())){
            nUsers.setRoleIds(usersParam.getRoleIds());
        }
        boolean ret=iUsersService.insertUsers(nUsers);
        if (ret){
            this.writeLog("添加用户");
        }
        return new ResponseBean(StatusCode.OK,null);

    }


    /**
     * 修改用户：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "修改用户", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("user:edit")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseBean updateUsers(
            @RequestBody UsersVO usersParam, HttpServletRequest request
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);


        if (Utils.notEmpty(usersParam.getId())) {

            // 修改用户
            UsersVO users = new UsersVO();
            users.setId(usersParam.getId());
            users.setUserName(usersParam.getUserName());
            if (Utils.notEmpty(usersParam.getRealName())) {
                users.setRealName(usersParam.getRealName());
            }
            if (Utils.notEmpty(usersParam.getTel())) {
                users.setTel(usersParam.getTel());
            }
            // 角色id集合
            if (Utils.notEmpty(usersParam.getRoleIds())) {// 角色id集合
                users.setRoleIds(usersParam.getRoleIds());
            }

            boolean ret = iUsersService.updateUsers(users);
            if (ret) {
                this.writeLog("修改用户");
            }
            return new ResponseBean(StatusCode.OK, null);
        } else {
            return new ResponseBean(StatusCode.OK_FAIL, null);
        }

    }

    /**
     * 删除用户（逻辑删除）：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "删除用户", notes = "登陆才能操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", dataType = "Integer", paramType = "query", required = true),
    })
    @RequiresAuthentication
    @RequiresPermissions("user:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public ResponseBean deleteUsers(@PathVariable Integer id,HttpServletRequest request) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);


        // 删除菜单
        UsersVO users = new UsersVO();
        users.setId(id);
        boolean ret = iUsersService.deleteUsers(users);
        if(ret){
            this.writeLog("删除用户");
        }
        return new ResponseBean(StatusCode.OK, null);

    }


    /**
     * 查看用户：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查询用户", notes = "登陆才能操作")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @RequiresAuthentication
    @RequiresPermissions("user:view")
    public ResponseBean selectUsers(
            @RequestBody UsersVO usersParam,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);


        UsersVO searchUsers = new UsersVO();
        searchUsers.setDelFlag(Const.DEL_FLAG_FALSE);
        if (Utils.notEmpty(usersParam.getUserName())) {
            searchUsers.setUserName(usersParam.getUserName());
        }
        if (Utils.notEmpty(usersParam.getTel())) {
            searchUsers.setTel(usersParam.getTel());
        }
        if (Utils.notEmpty(usersParam.getRoleIds())) {
            searchUsers.setRoleIds(usersParam.getRoleIds());
        }

        Page<UsersVO> page = new Page(currentPage, pageSize);

        page = iUsersService.pageUsers(page, searchUsers);
        return new ResponseBean(StatusCode.OK, page);
    }

    @ApiOperation(value = "用户修改密码", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("user:editPassword")
    @RequestMapping("/updateUserPassword")
    public ResponseBean updateUserPassword(@RequestBody UsersVO usersPassword,HttpServletRequest request) {
        // 获取登陆系统用户名 存日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);
        if (Utils.notEmpty(usersPassword.getNewPasswd()) && Utils.notEmpty(usersPassword.getOldPasswd())) {
            String userName = obj.toString();
            Users user = iUsersService.getUserByName(userName);
            if (user.getPasswd().equals(MD5Utils.getStringMD5(usersPassword.getOldPasswd()))) {
                user.setPasswd(MD5Utils.getStringMD5(usersPassword.getNewPasswd()));
                QueryWrapper<Users> updateByCondition = new QueryWrapper<>();
                updateByCondition.eq(Users.ID, user.getId());
                boolean update = iUsersService.update(user, updateByCondition);
                if (update) {
                    this.writeLog("用户修改密码");
                    return new ResponseBean(StatusCode.OK, null);
                } else {
                    return new ResponseBean(StatusCode.OK_FAIL, null);
                }
            } else {
                return new ResponseBean(StatusCode.USER_PWD_ERROR, null);
            }
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }
    }
}
